#include "MakeMediaData.h"
#include <math.h>

#define M_PI 3.14


CRandMediaData::CRandMediaData(int aSR, int aCh,int vW, int vH)
{
	t = 0;
	tincr = 2 * M_PI * 110.0 / aSR;	
	tincr2 = 2 * M_PI * 110.0 / aSR /aSR;

	picture = alloc_picture(PIX_FMT_YUV420P, vW, vH);

	width = vW;
	height = vH;
}

CRandMediaData::~CRandMediaData()
{
	av_free(picture->data[0]);
	av_free(picture);
}

void CRandMediaData::GetAudioData(int16_t *samples, int frame_size, int nb_channels)
{	
	if(!samples) return;
	int j, i, v;
	int16_t *q;

	q = samples;
	for(j=0;j<frame_size;j++) {
		v = (int)(sin(t) * 10000);
		for(i = 0; i < nb_channels; i++)
			*q++ = v;
		t += tincr;
		tincr += tincr2;
	}
}


AVFrame *CRandMediaData::alloc_picture(int pix_fmt, int width, int height)
{
	AVFrame *picture;
	uint8_t *picture_buf;
	int size;

	picture = avcodec_alloc_frame();
	if (!picture)
		return NULL;
	size = avpicture_get_size(pix_fmt, width, height);
	picture_buf = (uint8_t*)av_malloc(size);
	if (!picture_buf) {
		av_free(picture);
		return NULL;
	}
	avpicture_fill((AVPicture *)picture, picture_buf,
		pix_fmt, width, height);
	return picture;
}

AVFrame* CRandMediaData::GetYuvImage()
{	
	if(!picture ) return NULL;
	AVPicture* pict  = (AVPicture*)picture;
	int x, y;
	static int i = 0;
	/* Y */
	for(y=0;y<height;y++) {
		for(x=0;x<width;x++) {
			pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;
		}
	}

	/* Cb and Cr */
	for(y=0;y<height/2;y++) {
		for(x=0;x<width/2;x++) {
			pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2;
			pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5;
		}
	}
	i++;
	return picture;
}